package com.whj.wkpt.controller;

import com.whj.wkpt.entity.DeliveryAttachment;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.DeliveryAttachmentService;
import com.whj.wkpt.service.TaskApplicationService;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/freelancer/task-applications")
public class FreelancerTaskApplicationController {

    @Autowired
    private TaskApplicationService taskApplicationService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private DeliveryAttachmentService deliveryAttachmentService;

    @Value("${upload.path:uploads}")
    private String uploadPath;

    // 查看我的任务承接列表
    @GetMapping("")
    public String listMyTaskApplications(
            @RequestParam(required = false) String status,
            Model model, 
            Authentication authentication) {
        
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        List<TaskApplication> applications = null;
        Map<Long, Task> taskMap = new HashMap<>();
        if (currentUser != null) {
            applications = taskApplicationService.findByFreelancerId(currentUser.getUserId());
            // 如果指定了状态，则进行过滤
            if (status != null && !status.isEmpty()) {
                applications = applications.stream()
                    .filter(app -> status.equals(app.getDeliveryStatus()))
                    .toList();
            }
            
            // 为每个申请获取对应的任务信息
            for (TaskApplication app : applications) {
                Task task = taskService.findById(app.getTaskId());
                taskMap.put(app.getApplicationId(), task);
            }
        }
        
        model.addAttribute("applications", applications);
        model.addAttribute("taskMap", taskMap);
        model.addAttribute("searchStatus", status);
        return "freelancer/my-applications";
    }

    // 查看任务承接详情
    @GetMapping("/{applicationId}")
    public String viewTaskApplication(@PathVariable Long applicationId, 
                                     Model model, 
                                     Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        TaskApplication application = taskApplicationService.findById(applicationId);
        
        // 确保用户只能查看自己的申请
        if (application != null && currentUser != null 
            && application.getFreelancerId().equals(currentUser.getUserId())) {
            model.addAttribute("taskApplication", application);
            
            // 获取任务信息
            Task task = taskService.findById(application.getTaskId());
            model.addAttribute("task", task);
            
            // 获取附件列表
            List<DeliveryAttachment> attachments = deliveryAttachmentService.findByApplicationId(applicationId);
            // 确保attachments不为null
            if (attachments == null) {
                attachments = new ArrayList<>();
            }
            model.addAttribute("attachments", attachments);
            
            return "freelancer/task-application-detail";
        }
        
        return "redirect:/freelancer/task-applications";
    }

    // 跳转到提交成果物页面
    @GetMapping("/{applicationId}/submit-delivery")
    public String showSubmitDeliveryPage(@PathVariable Long applicationId, Model model) {
        TaskApplication application = taskApplicationService.findById(applicationId);
        if (application != null) {
            model.addAttribute("taskApplication", application);
            
            // 获取任务信息
            Task task = taskService.findById(application.getTaskId());
            model.addAttribute("task", task);
            
            // 获取附件列表
            List<DeliveryAttachment> attachments = deliveryAttachmentService.findByApplicationId(applicationId);
            model.addAttribute("attachments", attachments);
        }
        return "freelancer/submit-delivery";
    }
    
    // 提交成果物（带附件上传）
    @PostMapping("/{applicationId}/submit-delivery")
    public String submitDelivery(@PathVariable Long applicationId, 
                             @RequestParam("attachments") MultipartFile[] attachments,
                             Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            TaskApplication application = taskApplicationService.findById(applicationId);
            // 确保是当前用户的应用且状态为未交付
            if (application != null && application.getFreelancerId().equals(currentUser.getUserId())
                && "not_delivered".equals(application.getDeliveryStatus())) {
                application.setDeliveryStatus("delivered");
                application.setDeliveryTime(LocalDateTime.now());
                taskApplicationService.updateApplication(application);
                
                // 处理附件上传
                if (attachments != null && attachments.length > 0) {
                    for (MultipartFile file : attachments) {
                        if (!file.isEmpty()) {
                            try {
                                // 创建上传目录
                                Path uploadDir = Paths.get(uploadPath);
                                if (!Files.exists(uploadDir)) {
                                    Files.createDirectories(uploadDir);
                                }
                                
                                // 生成唯一文件名
                                String originalFileName = file.getOriginalFilename();
                                String fileExtension = "";
                                if (originalFileName != null && originalFileName.contains(".")) {
                                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                                }
                                String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
                                
                                // 保存文件
                                Path filePath = uploadDir.resolve(uniqueFileName);
                                Files.copy(file.getInputStream(), filePath);
                                
                                // 保存附件信息到数据库
                                DeliveryAttachment attachment = new DeliveryAttachment();
                                attachment.setApplicationId(applicationId);
                                attachment.setFileName(originalFileName);
                                attachment.setFilePath(filePath.toString());
                                attachment.setFileSize(file.getSize());
                                deliveryAttachmentService.createAttachment(attachment);
                            } catch (IOException e) {
                                // 处理文件上传错误
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        
        return "redirect:/freelancer/task-applications";
    }

    // 撤回已交付状态（仅在雇主未确认前可以撤回）
    @PostMapping("/{applicationId}/retract")
    public String retractTask(@PathVariable Long applicationId, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            TaskApplication application = taskApplicationService.findById(applicationId);
            // 确保是当前用户的应用且状态为已交付
            if (application != null && application.getFreelancerId().equals(currentUser.getUserId())
                && "delivered".equals(application.getDeliveryStatus())) {
                application.setDeliveryStatus("not_delivered");
                application.setDeliveryTime(null);
                taskApplicationService.updateApplication(application);
            }
        }
        
        return "redirect:/freelancer/task-applications";
    }
    
    // 下载附件
    @GetMapping("/attachment/{attachmentId}")
    public ResponseEntity<Resource> downloadAttachment(@PathVariable Long attachmentId) {
        try {
            DeliveryAttachment attachment = deliveryAttachmentService.findById(attachmentId);
            if (attachment != null) {
                Path filePath = Paths.get(attachment.getFilePath());
                if (Files.exists(filePath)) {
                    Resource resource = new UrlResource(filePath.toUri());
                    
                    // 正确处理包含中文字符的文件名
                    String encodedFileName = URLEncoder.encode(attachment.getFileName(), StandardCharsets.UTF_8.toString())
                            .replaceAll("\\+", "%20");
                    
                    return ResponseEntity.ok()
                            .header(HttpHeaders.CONTENT_DISPOSITION, 
                                    "attachment; filename*=UTF-8''" + encodedFileName)
                            .body(resource);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.notFound().build();
    }
}